package cn.com.doone.common.uc.shiro.filter;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.util.StringUtils;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;

import cn.com.doone.common.uc.service.OauthService;
import cn.com.doone.common.uc.web.WebUtils;

public class SecurityFilter extends AuthorizationFilter {

	private String unauthorizedUrl = "/unauthorized";  
	private OauthService oauthService;

	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
		// TODO Auto-generated method stub
		
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		
		String ip = WebUtils.retrieveClientIp(httpRequest);
		
		boolean validIp = oauthService.valiIPBlackList(ip);
		
		if (validIp) {
			return false;
		}
		
		return true;
	}
	
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) {  
		try {
			if (StringUtils.hasText(unauthorizedUrl)) { // 如果有未授权页面跳转过去  
				// org.apache.shiro.web.util.WebUtils.issueRedirect(request, response, unauthorizedUrl);
				org.apache.shiro.web.util.WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);  
			} else { // 否则返回401未授权状态码  
				org.apache.shiro.web.util.WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);  
			}  
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
		return false;  
	}  

	public void setOauthService(OauthService oauthService) {
		this.oauthService = oauthService;
	}
	
	
}
